<?php

declare(strict_types=1);
/**
 * 
 */
namespace WanZ\App\User\Consumer;

use WanZ\App\User\Consumer\AbstractConsumer;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

class Sms extends AbstractConsumer
{
    /**
     * 发送短信处理（包含：短信验证码、短信信息等，根据type来区分）
     * 
     * @return bool
     * @throws CommonException
     */
    public function sendCodeHandle(): bool
    {
        $result = $this->httpRequest()->postJson($this->getUrl().'/sms/index', [
            'company_id' => $this->getCompanyId(),
            'mobile'     => $this->data['phone'],
            'type'       => $this->data['type']
        ]);

        if ($result['code'] != 1) {
            throw new CommonException(ErrorCode::THIRD_API_ERROR, '验证码发送失败: '. $result['message']);
        }

        return true;
    }

    /**
     * 验证码校验处理
     *
     * @return bool
     * @throws CommonException
     */
    public function verifyCode(): bool
    {     
        $result = $this->httpRequest()->postJson($this->getUrl().'/sms/validate', [
            'mobile' => $this->data['phone'],
            'code'   => $this->data['verifyCode'],
            'type'   => $this->data['type']
        ]);

        if ($result['code'] != 1) {
            if (!isset($result['message'])) {
                throw new CommonException(ErrorCode::THIRD_API_ERROR, '验证码错误或已使用');
            }

            if ($result['message'] == '验证失败') {
                throw new CommonException(ErrorCode::THIRD_API_ERROR, '验证码错误或已使用');
            }

            throw new CommonException(ErrorCode::THIRD_API_ERROR, $result['message']);
        }

        return true;
    }

    /**
     * 获取短信配置信息
     *
     * @param $key
     * @return mixed
     * @throws CommonException
     */
    private function getConfig($key)
    {
        $config = config('redis.phone_code');

        if (!isset($config[$key])) {
            throw new CommonException(ErrorCode::THIRD_API_ERROR, '验证码处理错误：key值不存在');
        }

        return $config[$key];
    }

}
